<?php

declare(strict_types=1);

namespace App\Model;

use App\Helpers\ConfigUtil;
use App\Model\Service\NewGirlReplyPackageService;
use Hyperf\DbConnection\Model\Model;
use Hyperf\DbConnection\Db;

/**
 * 用户虚拟账户
 */
class UserCoin extends Model
{
    protected $table = 'user_coin';

    protected $fillable = [
        'user_id', 'recharge_coin', 'income_coin', 'total_income_coin', 'freeze_coin'
    ];

    public function userItem()
    {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    /**
     * 获取用户虚拟账户信息
     */
    static function getUserInfo($userId = 0)
    {
        $item = self::where('user_id', $userId)->first();
        $recharge = $item ? $item->recharge_coin : 0;
        $income = $item ? $item->income_coin : 0;
        $totalIncome = $item ? $item->total_income_coin : 0;
        $freezeCoin = $item ? $item->freeze_coin : 0;
        return [
            //充值金额
            'recharge_coin' => $recharge < 0 ? 0 : $recharge,
            //收入金额
            'income_coin' => $income < 0 ? 0 : $income,
            //累计收入
            'total_income_coin' => $totalIncome < 0 ? 0 : $totalIncome,
            //净余额
            'total_coin' => $recharge + $income - $freezeCoin,
            //总余额
            'real_total_coin' => $recharge + $income,
        ];
    }

    /**
     * 添加记录
     */
    static function addRecord($userId = 0, $check = false)
    {
        if ($check) {
            $item = self::where('user_id', $userId)->first();
            if ($item) return $item->toArray();
        }
        return self::create([
            'user_id' => $userId,
            'recharge_coin' => 0,
            'income_coin' => 0,
            'total_coin' => 0,
        ]);
    }

    /**
     * 消费金币（先充值账户，后收入账户）
     */
    static function costCoin($userId = 0, $cost = 0, $userCoinInfo = [])
    {
        if (!$cost || !$userId || !$userCoinInfo || $cost <= 0) return false;

        //充值余额够
        if ($userCoinInfo['recharge_coin'] >= $cost) {
            self::where('user_id', $userId)->decrement('recharge_coin', $cost);
            $ret = [
                'recharge_coin' => $userCoinInfo['recharge_coin'] - $cost,
                'income_coin' => $userCoinInfo['income_coin'],
            ];
        }
        //充值余额不够
        else {
            $offcost = $cost - $userCoinInfo['recharge_coin'];
            //收入余额够
            if ($userCoinInfo['income_coin'] >= $offcost) {
                self::where('user_id', $userId)->update(['recharge_coin' => 0]);
                self::where('user_id', $userId)->decrement('income_coin', $offcost);
                $ret = [
                    'recharge_coin' => 0,
                    'income_coin' => $userCoinInfo['income_coin'] - $offcost,
                ];
            }
            //收入余额不够
            else {
                self::where('user_id', $userId)->update(['income_coin' => 0, 'recharge_coin' => 0]);
                $ret = [
                    'recharge_coin' => 0,
                    'income_coin' => 0,
                ];
            }
        }
        return $ret;
    }

    /**
     * 增加收入
     */
    static function gainIncome($userId = 0, $incomeCoin = 0)
    {
        if (!$incomeCoin || !$userId || $incomeCoin <= 0) return false;
        //添加记录
        $record = self::addRecord($userId, true);
        self::where('user_id', $userId)->increment('income_coin', $incomeCoin);
        self::where('user_id', $userId)->increment('total_income_coin', $incomeCoin);

        $newGirlTaskValid = config('act.new_girl_task_valid', '2023-03-12');
        $profile = UserProfile::getProfile($userId);
        if ($profile->gender == 0 && $profile->created_at >= $newGirlTaskValid) {
            if ($record['income_coin'] + $incomeCoin >= 50) {
                NewGirlReplyPackageService::coinCanWithdraw((int)$userId);
            }
        }

        //给用户透传消息
        Message::sendSlient($userId, 'USER_COIN_CHANGE');
        return [
            'recharge_coin' => $record['recharge_coin'],
            'income_coin' => $record['income_coin'] + $incomeCoin
        ];
    }

    /**
     * 增加充值收入
     */
    static function gainRecharge($userId = 0, $addCoin = 0)
    {
        if (!$addCoin || !$userId) return false;
        //添加记录
        $record = self::addRecord($userId, true);
        self::where('user_id', $userId)->increment('recharge_coin', $addCoin);
        return [
            'recharge_coin' => $record['recharge_coin'] + $addCoin,
            'income_coin' => $record['income_coin'],
        ];
    }

    /**
     * 扣除收入账户
     */
    static function decIncome($userId = 0, $incomeCoin = 0)
    {
        if (!$incomeCoin || !$userId) return false;
        $record = self::where('user_id', $userId)->first();
        if (!$record) return false;
        $ret = self::where('user_id', $userId)->decrement('income_coin', $incomeCoin);
        return [
            'recharge_coin' => $record['recharge_coin'],
            'income_coin' => $record['income_coin'] - $incomeCoin
        ];
    }

    /**
     * 冻结资金
     */
    static function freezeCoin($userId = 0, $coin = 0)
    {
        if (!$userId || !$coin) return false;
        log_info(__METHOD__ . "=={$userId}==Coin:{$coin}");
        return self::where('user_id', $userId)->update(['freeze_coin' => $coin]);
    }

    /**
     * 清空冻结账户
     */
    static function clearFreezeCoin($userId = 0)
    {
        if (!$userId) return false;
        log_info(__METHOD__ . "=={$userId}");
        return self::where('user_id', $userId)->update(['freeze_coin' => 0.0]);
    }

    /**
     * 获取总充值账户余额
     * @return mixed
     */
    static function getTotalRechargeCoin()
    {
        return self::sum('recharge_coin');
    }
}
